/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo14.controller;

import cn.edu.zua.demo14.entity.QTestGoodsInfoEntity;
import cn.edu.zua.demo14.entity.TestGoodsInfoEntity;
import cn.edu.zua.demo14.jpa.TestGoodsInfoJpa;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/28 15:35
 */
@RestController
public class QueryController {
    private TestGoodsInfoJpa goodsInfoJpa;
    private EntityManager entityManager;

    @Autowired
    public QueryController(TestGoodsInfoJpa goodsInfoJpa, EntityManager entityManager) {
        this.goodsInfoJpa = goodsInfoJpa;
        this.entityManager = entityManager;
    }

    @GetMapping(path = "/query")
    public List<TestGoodsInfoEntity> query() {
        // queryDSL查询实体
        QTestGoodsInfoEntity entity = QTestGoodsInfoEntity.testGoodsInfoEntity;
        // 构建JPA查询接口
        JPAQuery<TestGoodsInfoEntity> queryJpa = new JPAQuery<>(entityManager);
        // 返回查询接口
        return queryJpa
                // 查询字段
                .select(entity)
                // 查询表
                .from(entity)
                // 查询条件
                .where(entity.category.id.eq(1L))
                // 返回结果
                .fetch();
    }

    /**
     * spring data jpa 整合queryDSL完成查询
     * @return List
     */
    @GetMapping("/join")
    @SuppressWarnings("Duplicates")
    public List<TestGoodsInfoEntity> join() {
        // queryDSL查询实体
        QTestGoodsInfoEntity goods = QTestGoodsInfoEntity.testGoodsInfoEntity;
        // 查询条件
        BooleanExpression expresion = goods.category.id.eq(1L);
        Iterator<TestGoodsInfoEntity> it = goodsInfoJpa.findAll(expresion).iterator();
        List<TestGoodsInfoEntity> list = new ArrayList<>();
        // 转List
        while (it.hasNext()) {
            list.add(it.next());
        }
        return list;
    }

    /**
     * spring data jpa 整合queryDSL完成查询
     * @return List
     */
    @GetMapping("/join2")
    @SuppressWarnings("Duplicates")
    public List<TestGoodsInfoEntity> join2() {
        // queryDSL查询实体
        QTestGoodsInfoEntity goods = QTestGoodsInfoEntity.testGoodsInfoEntity;
        // 自定义查询对象
        InQuirer inQuirer = new InQuirer();
        // 添加查询条件
        inQuirer.putExpression(goods.category.id.eq(1L));
        // 返回查询结果
        return inQuirer.iteratorToList(goodsInfoJpa.findAll(inQuirer.buildQuery()));
    }
}
